package spinning

import (
	"encoding/json"
	"fmt"

	mqtt "github.com/eclipse/paho.mqtt.golang"
	_ "github.com/mattn/go-sqlite3"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"

	"github.com/edgexfoundry/app-functions-sdk-go/v2/pkg/interfaces"
	"github.com/edgexfoundry/app-functions-sdk-go/v2/pkg/util"
)

func (app *SpinningApp) handleMcuSettingsMsg(appContext interfaces.AppFunctionContext, data interface{}) (bool, interface{}) {
	// 处理 从 MCU 发送来的消息
	fmt.Println("### edgex/event/mcu/setting begin ###")
	input, err := util.CoerceType(data)

	if err != nil {
		appContext.LoggingClient().Error(err.Error())
		return false, err
	}

	// 1 将MCU发送来的数据 保存到  mcuSettings,
	err2 := json.Unmarshal(input, &app.mcuSettings)
	if err2 != nil {
		panic(err2)
	}

	// 2 保存到本地 数据库
	//machine_db, err3 := sql.Open("sqlite3", "mcu_settings.db")
	mcu_settings_db, err3 := gorm.Open(sqlite.Open("mcu_settings.db"), &gorm.Config{})
	if err3 != nil {
		appContext.LoggingClient().Info(err3.Error())
	}

	var mcuSettings = McuSettings{}
	mcu_settings_db.First(&mcuSettings, "name = ?", app.mcuSettings.Name)
	mcu_settings_db.Model(&mcuSettings).Updates(&app.mcuSettings)

	appContext.LoggingClient().Info("handleMachineMsg")
	appContext.SetResponseData([]byte("success"))

	fmt.Println("### edgex/event/mcu/setting end ###")
	return false, nil
}

func (app *SpinningApp) handleMqttSettingsMsg(client mqtt.Client, message mqtt.Message) {
	// 处理 从 MCU 发送来的消息
	fmt.Println("### edgex/event/mcu/setting begin ###")

	// 1 将MCU发送来的数据 保存到  mcuSettings,
	var request map[string]interface{}
	err := json.Unmarshal(message.Payload(), &request)
	if err != nil {
		fmt.Printf("Error unmarshaling payload: %s\n", err)
		return
	}

	// 2 保存到本地 数据库
	//machine_db, err3 := sql.Open("sqlite3", "mcu_settings.db")
	mcu_settings_db, err3 := gorm.Open(sqlite.Open("mcu_settings.db"), &gorm.Config{})
	if err3 != nil {
		fmt.Println(err3.Error())
	}

	var mcuSettings = McuSettings{}
	mcu_settings_db.First(&mcuSettings, "name = ?", app.mcuSettings.Name)
	mcu_settings_db.Model(&mcuSettings).Updates(&app.mcuSettings)

	fmt.Println("### edgex/event/mcu/setting end ###")
}
